package com.kuangstudy.service.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class CacheService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成自增的id
     * @param key
     * @return
     */
    public Long getIncrementNum(String key) {
        // 不存在 准备创建 键值对
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        // 计数器累加 
        Long counter = entityIdCounter.incrementAndGet();
        // log.info("=========================>"+ counter);
        if ((null == counter || counter.longValue() == 1)) { // 初始设置过期时间
            System.out.println("设置过期时间为1天!");
            // 设置清除的目的，是让每天的计数器都从0开始，因为生成好的key后面不用了不如让他删除掉
            entityIdCounter.expire(1, TimeUnit.DAYS); // 单位天
        }
        return counter;
    }
}